import os
import numpy as np
from PIL import Image
import tensorflow as tf
import sys

if __name__ != '__main__':
    import settings
    MODEL = settings.MODEL_DIR


def read_image(filename, width=120, height=100):
    im = Image.open(filename).convert('L').resize((width, height), Image.ANTIALIAS)
    return np.asarray(im)


def apply_model(filename):
    batch_x = read_image(filename)

    saver = tf.train.import_meta_graph(os.path.join(MODEL, 'cnn-n.ckpt.meta'))
    graph = tf.get_default_graph()

    predict = graph.get_tensor_by_name('forword-prop/predict:0')
    keep_prob = graph.get_tensor_by_name('dropout/keep_prob:0')
    x = graph.get_tensor_by_name('input/x:0')

    with tf.Session() as sess:
        saver.restore(sess, tf.train.latest_checkpoint(MODEL))
        res = sess.run(predict, feed_dict={x: np.array([batch_x]), keep_prob: 1.0})

    return ''.join(map(str, res[0]))


def main(_):
    return apply_model(_[1])


if __name__ == '__main__':
    MODEL = '/mnt/data/prod/cnn-captcha-model/'
    tf.app.run(main=main, argv=sys.argv)
